<template>
  <div class="system-logs">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">系统日志</span>
          <div class="header-actions">
            <el-button @click="exportLogs" :loading="exporting">
              <el-icon><Download /></el-icon>
              导出日志
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <el-row :gutter="16" class="stats-row">
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon today">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.today_logins || 0 }}</div>
                <div class="stat-title">今日登录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon week">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getTotalWeekLogins }}</div>
                <div class="stat-title">本周登录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon online">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.online_users || 0 }}</div>
                <div class="stat-title">在线用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.active_users?.length || 0 }}</div>
                <div class="stat-title">活跃用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon failed">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.failed_logins_today || 0 }}</div>
                <div class="stat-title">今日失败</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total_logins || 0 }}</div>
                <div class="stat-title">总登录数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 搜索筛选 -->
      <div class="search-bar">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-select v-model="searchForm.user_id" placeholder="选择用户" clearable filterable>
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.username} (${user.first_name} ${user.last_name})`"
                :value="user.id"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-input
              v-model="searchForm.ip_address"
              placeholder="IP地址"
              clearable
            />
          </el-col>
          <el-col :span="5">
            <el-date-picker
              v-model="searchForm.start_date"
              type="date"
              placeholder="开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="5">
            <el-date-picker
              v-model="searchForm.end_date"
              type="date"
              placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 日志表格 -->
      <el-table
        v-loading="loading"
        :data="logList"
        style="width: 100%"
        :default-sort="{ prop: 'login_time', order: 'descending' }"
      >
        <el-table-column prop="user.username" label="用户名" width="120" />
        <el-table-column label="用户姓名" width="120">
          <template #default="{ row }">
            {{ row.user?.first_name }} {{ row.user?.last_name }}
          </template>
        </el-table-column>
        <el-table-column prop="user.role_display" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.user?.role)">
              {{ row.user?.role_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip_address" label="IP地址" width="140" />
        <el-table-column prop="user_agent" label="浏览器" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatUserAgent(row.user_agent) }}
          </template>
        </el-table-column>
        <el-table-column prop="login_time" label="登录时间" width="160" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.login_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="logout_time" label="退出时间" width="160">
          <template #default="{ row }">
            {{ row.logout_time ? formatDateTime(row.logout_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="在线时长" width="120">
          <template #default="{ row }">
            {{ calculateDuration(row.login_time, row.logout_time) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.logout_time ? 'info' : 'success'">
              {{ row.logout_time ? '已退出' : '在线' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 活跃用户详情对话框 -->
    <el-dialog
      v-model="activeUsersDialogVisible"
      title="活跃用户详情"
      width="600px"
    >
      <el-table :data="statistics.active_users" style="width: 100%">
        <el-table-column prop="user__username" label="用户名" />
        <el-table-column label="姓名">
          <template #default="{ row }">
            {{ row.user__first_name }} {{ row.user__last_name }}
          </template>
        </el-table-column>
        <el-table-column prop="login_count" label="登录次数" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Calendar, TrendCharts, User, UserFilled, Warning,
  DataAnalysis, Download
} from '@element-plus/icons-vue'
import { loginLogApi, userManageApi } from '@/api/system'
import { formatDateTime } from '@/utils/format'

// 响应式数据
const loading = ref(false)
const exporting = ref(false)
const logList = ref([])
const userList = ref([])
const statistics = ref<any>({})
const activeUsersDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  user_id: '',
  ip_address: '',
  start_date: '',
  end_date: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 计算属性
const getTotalWeekLogins = computed(() => {
  if (!statistics.value.daily_statistics) return 0
  return Object.values(statistics.value.daily_statistics).reduce((sum: number, count: any) => sum + count, 0)
})

// 方法
const fetchLogList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }
    
    const response = await loginLogApi.getLoginLogs(params)
    logList.value = response.data .results
    pagination.total = response.data .count
  } catch (error) {
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

const fetchStatistics = async () => {
  try {
    const response = await loginLogApi.getStatistics()
    statistics.value = response
  } catch (error) {
    ElMessage.error('获取统计信息失败')
  }
}

const fetchUserList = async () => {
  try {
    const response = await userManageApi.getUserList({ page_size: 1000 })
    userList.value = response.results
  } catch (error) {
    console.error('获取用户列表失败')
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchLogList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    user_id: '',
    ip_address: '',
    start_date: '',
    end_date: ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchLogList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchLogList()
}

const exportLogs = async () => {
  exporting.value = true
  try {
    const params = {
      ...searchForm
    }

    // 调用导出API
    const response = await loginLogApi.exportLoginLogs(params)

    // 创建下载链接
    const blob = new Blob([response], { type: 'text/csv;charset=utf-8' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `login_logs_${new Date().toISOString().split('T')[0]}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('日志导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

const getRoleTagType = (role: string) => {
  const typeMap: Record<string, string> = {
    admin: 'danger',
    teacher: 'warning',
    student: 'info'
  }
  return typeMap[role] || 'info'
}

const formatUserAgent = (userAgent: string) => {
  if (!userAgent) return '-'
  
  // 简化用户代理字符串显示
  if (userAgent.includes('Chrome')) return 'Chrome'
  if (userAgent.includes('Firefox')) return 'Firefox'
  if (userAgent.includes('Safari')) return 'Safari'
  if (userAgent.includes('Edge')) return 'Edge'
  return 'Other'
}

const calculateDuration = (loginTime: string, logoutTime: string | null) => {
  if (!loginTime) return '-'
  
  const login = new Date(loginTime)
  const logout = logoutTime ? new Date(logoutTime) : new Date()
  const duration = logout.getTime() - login.getTime()
  
  const hours = Math.floor(duration / (1000 * 60 * 60))
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchLogList(),
    fetchStatistics(),
    fetchUserList()
  ])
})
</script>

<style lang="scss" scoped>
.system-logs {
  .page-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: 600;
        color: var(--text-color-primary);
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .stats-row {
    margin-bottom: 24px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          margin-right: 16px;
          
          .el-icon {
            font-size: 24px;
          }
          
          &.today {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.week {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.online {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.active {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
          }

          &.failed {
            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
          }

          &.total {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: 600;
            color: var(--text-color-primary);
            line-height: 1;
            margin-bottom: 4px;
          }
          
          .stat-title {
            font-size: 14px;
            color: var(--text-color-secondary);
          }
        }
      }
    }
  }
  
  .search-bar {
    margin-bottom: 20px;
    padding: 20px;
    background: var(--bg-color-light);
    border-radius: 8px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
